package com.omega_r.omegarecyclerview.sections_example;


import com.omega_r.libs.omegarecyclerview.base.BaseProvider;
import com.omega_r.libs.omegarecyclerview.base.BaseViewHolder;
import com.omega_r.omegarecyclerview.ResourceTable;
import com.omega_r.omegarecyclerview.pagination_example.Image;
import com.omega_r.omegarecyclerview.pagination_example.ImageViewHolder;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.Component;
import ohos.agp.components.LayoutScatter;
import ohos.agp.components.ListContainer;
import ohos.agp.components.Text;
import ohos.agp.window.dialog.ToastDialog;
import ohos.utils.net.Uri;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedHashSet;
import java.util.Set;


public class SectionsAbility extends Ability implements Component.ClickedListener {


    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        setUIContent(ResourceTable.Layout_ability_sections);
        ListContainer omegaRecyclerView = (ListContainer) findComponentById(ResourceTable.Id_recyclerview);
        Component header = LayoutScatter.getInstance(this).parse(ResourceTable.Layout_item_text_header, null, false);
        Component footer = LayoutScatter.getInstance(this).parse(ResourceTable.Layout_item_text_footer, null, false);
        header.setClickedListener(this);
        footer.setClickedListener(this);
        BaseProvider adapter = new BaseProvider(getContext(), Image.createImageList(4)
                , ResourceTable.Layout_item_image);
        adapter.setHeaderComponent(header);
        adapter.setFooterComponent(footer);
        adapter.setComponentBindingListener(new BaseProvider.ComponentBindingListener() {
            @Override
            public BaseViewHolder creatViewHolder(Component item) {
                return new ImageViewHolder(item);
            }

            @Override
            public void initData(BaseViewHolder baseViewHolder, Object object, int position) {
                ((ImageViewHolder) baseViewHolder).updateView((Image) object,position);
            }
        });
        omegaRecyclerView.setItemProvider(adapter);
    }


    @Override
    public void onClick(Component component) {
        switch (component.getId()) {
            case ResourceTable.Id_textview_header:
                showToast("Header clicked");
                break;
            case ResourceTable.Id_textview_footer:
                //发送邮件
                startAbility(build());
                break;
        }
    }

    public Intent build() {
        Uri mailtoUri = constructMailtoUri();
        Intent intent = new Intent();
        Operation operation = new Intent.OperationBuilder().withDeviceId("").withAction("android.intent.action.SENDTO").build();
        intent.setOperation(operation);
        intent.addFlags(Intent.FLAG_NOT_OHOS_COMPONENT);
        intent.setUri(mailtoUri);
        return intent;
    }


    private Uri constructMailtoUri() {
        StringBuilder mailto = new StringBuilder(1024);
        mailto.append("mailto:");
        Set<String> to = new LinkedHashSet<>();
        to.add(getEmail());
        addRecipients(mailto, to);

        boolean hasQueryParameters = false;
        hasQueryParameters = addQueryParameter(mailto, "subject", "Great library", hasQueryParameters);
        addQueryParameter(mailto, "body", "Hello world", hasQueryParameters);

        return Uri.parse(mailto.toString());
    }

    private boolean addQueryParameter(StringBuilder mailto, String field, String value, boolean hasQueryParameters) {
        if (value == null) {
            return hasQueryParameters;
        }

        mailto.append(hasQueryParameters ? '&' : '?').append(field).append('=').append(Uri.encode(value));

        return true;
    }

    private void addRecipients(StringBuilder mailto, Set<String> recipients) {
        if (recipients.isEmpty()) {
            return;
        }

        for (String recipient : recipients) {
            mailto.append(encodeRecipient(recipient));
            mailto.append(',');
        }

        mailto.setLength(mailto.length() - 1);
    }

    static String encodeRecipient(String recipient) {
        int index = recipient.lastIndexOf('@');
        String localPart = recipient.substring(0, index);
        String host = recipient.substring(index + 1);
        return Uri.encode(localPart) + "@" + Uri.encode(host);
    }

    public  String getEmail() {
        ohos.global.resource.ResourceManager resManager = getResourceManager();
        ohos.global.resource.RawFileEntry rawFileEntry = resManager.getRawFileEntry("resources/rawfile/test.txt");
        StringBuilder stringBuilder = new StringBuilder();
        try {
            BufferedReader bf = new BufferedReader(new InputStreamReader(
                    rawFileEntry.openRawFile()));
            String line;
            while ((line = bf.readLine()) != null) {
                stringBuilder.append(line);
            }
            return stringBuilder.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * Toast弹框
     *
     * @param content 内容
     */
    private void showToast(String content) {
        Component toastLayout = LayoutScatter.getInstance(this)
                .parse(ResourceTable.Layout_layout_toast, null, false);
        Text toastText = (Text) toastLayout.findComponentById(ResourceTable.Id_text_msg_toast);
        toastText.setText(content);
        new ToastDialog(this)
                .setComponent(toastLayout)
                .setTransparent(true)
                .show();
    }
}
